package com.program.facesigninsystem.controller;

import cn.yueshutong.springbootstartercurrentlimiting.annotation.CurrentLimiter;
import com.program.facesigninsystem.entity.*;
import com.program.facesigninsystem.service.IClassesService;
import com.program.facesigninsystem.service.IRewardService;
import com.program.facesigninsystem.service.ISignInActivityService;
import com.program.facesigninsystem.service.IUserInfoService;
import com.program.facesigninsystem.util.ChangeDate;
import com.program.facesigninsystem.util.GetInfoUtil;
import com.program.facesigninsystem.util.PageUtil;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.program.facesigninsystem.util.ScanCodeUtil.decodeCode;
import static com.program.facesigninsystem.util.ScanCodeUtil.encodeCode;


/***
 * @author Mapler
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/act")
public class SignInActivityController {
    private static Logger log = Logger.getLogger(SignInActivityController.class.toString());
    private static final int LOCATION = 522;
    private static final int CODE = 829;
    @Resource
    IRewardService iRewardService;
    @Resource
    ISignInActivityService iSignInActivityService;
    @Resource
    IUserInfoService iUserInfoService;
    @Resource
    IClassesService iClassesService;

    @RequestMapping(value = "/pubNewAct",method = RequestMethod.POST)
    public ResponseModel addNewActivity(@RequestBody JSONObject act){
        final int rewardPerTime = 30;
        final int dayMaxReward = 100;
        try{
            String actId = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(System.currentTimeMillis());
            String cid;
            try{ cid=act.getString("cid");}
            catch (Exception e){cid="";}
            iSignInActivityService.addNewActivity(actId, act.getString("title"), currentTime, act.getString("actType"),
                    act.getString("caption"), cid, act.getString("tid")
            );
            iUserInfoService.updateIssued(act.getString("tid"));
            Object[] listSession = act.getJSONArray("listSession").toArray();
            for (Object aListSession : listSession) {
                String lid = GetInfoUtil.getId();
                JSONObject temp = JSONObject.fromObject(aListSession);
                iSignInActivityService.addNewLink(lid, temp.getInt("linkType"), temp.getString("duration"),
                        temp.getString("startTime"), temp.getString("endTime"), temp.getInt("status"),
                        actId,temp.getDouble("location_x"), temp.getDouble("location_y"), temp.getDouble("range"));
            }
            String uid = act.getString("tid");
            Rewards rewards = iRewardService.selectReward(uid);
            String lastGainDay;
            String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0,10);
            //先判断列表是否有记录，没有则新增记录
            if(rewards == null){
                iRewardService.addNewRewards(uid, 0, 0, 0, 1,
                        currentDay, rewardPerTime, rewardPerTime);
            }else{
                //有则更新记录
                int limitFromRecordA = rewards.getLimit_from_record_a();
                int limitFromRecordB = rewards.getLimit_from_record_b();
                int limitFromRecordC = rewards.getLimit_from_record_c();
                int limitFromRecordActivity = rewards.getLimit_from_activity();
                lastGainDay = rewards.getLast_gain_day();
                int rewardPoints = rewards.getReward_points();
                if(!lastGainDay.equals(currentDay)) {
                    //如果上次获取积分的日期不等于今天，则直接新增一条记录，并将上次获取积分的日期改为今天
                    iRewardService.updateRewards(uid, 0, 0, 0, 1, currentDay, rewardPoints+rewardPerTime, rewardPerTime);
                }else {
                    //如果上次获取积分的日期等于今天
                    if(dayMaxReward<rewards.getDay_reward()) {
                        return new ResponseModel(200,"创建成功","今日获取总积分已达上限");
                    }
                    //判断是不是今天第一次获取
                    else if (limitFromRecordActivity == 0) {
                        iRewardService.updateRewards(uid, limitFromRecordA, limitFromRecordB, limitFromRecordC, 1, currentDay, rewardPoints+rewardPerTime, rewards.getDay_reward()+rewardPerTime);
                    }else{
                        return new ResponseModel(200,"创建成功","今日创建活动获取积分次数已达上限");
                    }
                }
            }
            return new ResponseModel(200,"创建成功","积分 +30");
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(168,"创建失败");
        }
    }

    @RequestMapping(value = "/findActByTid",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  void findActByTid(
            HttpServletResponse resp,
            @RequestParam("tid")String tid,
            @RequestParam(value = "createTime",required = false,defaultValue = "%")String createTime,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "20") int pageSize
    ){
        Object[] activityList = iSignInActivityService.selectActivityByTid(tid,createTime);
        List<JSONObject> data = new ArrayList<>();
        try{
            for (Object anActivityList : activityList) {
                JSONObject act = JSONObject.fromObject(anActivityList);
                String cid = act.getString("cid");
                if ((cid != null) && (!"".equals(cid))) {
                    Classes classes = iClassesService.selectClass(cid);
                    if (classes != null) {
                        act.accumulate("className", classes.getName());
                    } else {
                        act.accumulate("className", "");
                    }
                }
                act.remove("tid");
                Object[] linkList = iSignInActivityService.selectLinkByActId(act.getString("actId"));
                List<JSONObject> temp = new ArrayList<>();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = dateFormat.format(System.currentTimeMillis());
                for (Object aLinkList : linkList) {
                    JSONObject link = JSONObject.fromObject(aLinkList);
                    link.remove("actId");
                    if (currentTime.compareTo(link.getString("endTime")) > 0 && (!link.getString("endTime").equals(link.getString("startTime")))) {
                        link.put("status", 2);
                    }
                    temp.add(link);
                }
                act.accumulate("links", temp);
                data.add(act);
            }
            JSONObject data1 = PageUtil.wrap(data,"data",pageSize,pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }

    @RequestMapping(value = "/deleteActivity",method = RequestMethod.GET)
    public  ResponseModel deleteActivity(@RequestParam("actid")String actId){
        try {
            iSignInActivityService.deleteActivityByID(actId);
            return new ResponseModel(200,"删除成功");
        }catch(Exception e){
            return new ResponseModel(144,"删除失败");
        }
    }

    @RequestMapping(value = "/updateLinkStatus",method = RequestMethod.GET)
    public  ResponseModel updateLinkStatus(@RequestParam("lid")String lid,@RequestParam(value = "status")int status,@RequestParam("duration")String duration){
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = dateFormat.format(System.currentTimeMillis());
            long tmpDuration = Long.parseLong(duration);
            tmpDuration = tmpDuration*60*1000;
            String endTime = dateFormat.format(System.currentTimeMillis()+tmpDuration);
            iSignInActivityService.updateLinkStatus(lid,status,startTime,endTime);
            SignInLink signInLink = iSignInActivityService.selectLinkByLid(lid);
            if(signInLink.getRangement() == 0&&signInLink.getLocation_x() == 0&&signInLink.getLocation_y() == 0) {
                return new ResponseModel(200,"激活成功",LOCATION);
            }
            return new ResponseModel(200,"激活成功",CODE);
        }catch(Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(144,"激活失败");
        }
    }

    @RequestMapping(value = "/updateCode",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  ResponseModel updateCode(@RequestParam("lid")String lid){
        try{
            return new ResponseModel(200,"二维码获取成功",encodeCode(lid));
        }catch (Exception e){
            return new ResponseModel(143,"二维码获取失败");
        }
    }

    @RequestMapping(value = "/scanCode",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  ResponseModel scanCode(@RequestParam("code")String code){
        String invalidCode = "InvalidCode";
        String codeExpired = "CodeExpired";
        String decodeCode = decodeCode(code);
        if(invalidCode.equals(decodeCode)){
            return new ResponseModel(142,"无法识别的二维码");
        }else if(codeExpired.equals(decodeCode)){
            return new ResponseModel(141,"二维码已过期");
        }
        return new ResponseModel(200,"扫描二维码成功",decodeCode);
    }

    @CurrentLimiter(QPS=5)
    @RequestMapping(value = "/selectActivityByMonth",method = RequestMethod.GET)
    public  ResponseModel selectActivityByMonth(@RequestParam("tid")String tid,@RequestParam("month")String month){
        try{
            List<Integer> outDays = new ArrayList<>();
            List<SignInActivity> days = iSignInActivityService.selectActivityByMonth(tid,month);
            Iterator iterator = days.iterator();
            int day;
            SignInActivity signInActivity;
            while (iterator.hasNext()){
                signInActivity = (SignInActivity)iterator.next();
                day = Integer.parseInt(signInActivity.getCreateTime().substring(8,10));
                if(!outDays.contains(day)) {
                    outDays.add(day);
                }
            }
            return new ResponseModel(200,"获取成功",outDays);
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(139,"获取失败");
        }
    }

    @RequestMapping(value = "/selectList",method = RequestMethod.GET)
    public void selectList(HttpServletResponse resp, @RequestParam(value = "tid")String tid,
                            @RequestParam(value = "pageNum", required = false ,defaultValue = "1") int pageNum,
                            @RequestParam(value = "pageSize", required = false ,defaultValue = "10") int pageSize){
        try {
            List<Map<String,Object>> mapList=iSignInActivityService.selectList(tid);
            try {
                JSONObject jsonObject = PageUtil.wrap2(mapList,"Activity",pageSize,pageNum);
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
        }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }

    @RequestMapping(value = "/linkList",method = RequestMethod.GET)
    public void selectLinkList(HttpServletResponse resp, @RequestParam(value = "actid")String actid,
                            @RequestParam(value = "pageNum", required = false ,defaultValue = "1") int pageNum,
                            @RequestParam(value = "pageSize", required = false ,defaultValue = "10") int pageSize){
        try {
            List<SignInLink> signInLinks=iSignInActivityService.selectLinkList(actid);
            ChangeDate changeDate = new ChangeDate();
            Date date = new Date(System.currentTimeMillis());
            for (SignInLink signInLink : signInLinks) {
                changeDate.setSettime(signInLink.getEndTime());
                if (date.after(changeDate.settime) && !signInLink.getEndTime().equals(signInLink.getStartTime())) {
                    signInLink.setStatus(2);
                }
            }
            try {
                JSONObject jsonObject = PageUtil.wrap3(signInLinks,"Link",pageSize,pageNum);
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
            }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }
}
